package com.ice.framework.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.IBinder
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.ice.framework.dialog.LoadingDialog
import com.ice.framework.event.NullEvent
import com.ice.framework.utils.ToastUtil
import com.jaeger.library.StatusBarUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseActivity<T:BaseViewModel,T1:ViewBinding> : AppCompatActivity() {

    companion object{
        val activityTasks=ArrayList<Activity>()
    }

    protected fun getHtmlData(htmlBody: String?): String {
        val head = ("<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:100%; height:auto;}*{margin:0px;}</style>"
                + "</head>")
        if (TextUtils.isEmpty(htmlBody)) {
            val empty = "<p>/<p>"
            return "<html>$head<body>$empty</body></html>"
        }
        return "<html>$head<body>$htmlBody</body></html>"
    }

    lateinit var viewModel: T

    lateinit var binding : T1

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val view:View? = currentFocus
            if (isHideInput(view,ev)){
                hideSoftInput(view!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    // 判定是否需要隐藏
    private fun isHideInput(v: View?, ev: MotionEvent):Boolean {
        if(v!=null&& v is EditText){
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = left + v.getWidth()
            return !(ev.x > left && ev.x < right && ev.y > top
                    && ev.y < bottom)
        }
        return false
    }

    // 隐藏软键盘
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(
                    token,
                    InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    @Suppress("UNUSED_PARAMETER", "RedundantVisibilityModifier")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onNull(nullEvent: NullEvent){}

    private lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }
        activityTasks.add(this)
        StatusBarUtil.setColor(this,IceApplication.statusBarColor,0)
        StatusBarUtil.setDarkMode(this)
        binding=initViewBinding()
        setContentView(binding.root)
        viewModel=ViewModelProvider(this).get(initViewModel())
        viewModel.toastMsg.observe(this) {
            ToastUtil.show(it)
        }
        loadingDialog= LoadingDialog(this, window.decorView as ViewGroup)
        viewModel.showProgressBar.observe(this) {
            if (it) {
                if (!loadingDialog.isShowing) {
                    loadingDialog.show()
                }
            } else {
                if (loadingDialog.isShowing) {
                    loadingDialog.dismiss()
                }
            }
        }
        initObserver()
        initView()
    }

    abstract fun initViewModel():Class<T>

    abstract fun initViewBinding():T1

    override fun onStart() {
        super.onStart()
        initData()
    }

    //初始化监听
    abstract fun initObserver()

    //初始化数据
    abstract fun initData()

    //初始化View
    abstract fun initView()

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        activityTasks.remove(this)
    }


}
